﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Zyg.SSO.Core.Business;

namespace Zyg.SSO.Web.Admin.Account
{
    public partial class AdminList : Zyg.SSO.Web.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (!base.Account.HavePermission(Permission.AdminManage))
                {
                    throw new Exception("你无权查看此页面");
                }
                BindData();
            }
        }

        private void BindData()
        {
            IList<Zyg.SSO.Core.Business.Account> accounts = Zyg.SSO.Core.Business.Account.GetAccountsByAdminType(true);

            GridViewAccountList.DataSource = Zyg.SSO.Core.Business.Account.ToDataTable(accounts);
            GridViewAccountList.DataBind();
        }

        protected void BtnDelete_Click(object sender, EventArgs e)
        {
            bool hasApp = false;

            for (int i = GridViewAccountList.Rows.Count - 1; i > -1; i--)
            {
                CheckBox cb = GridViewAccountList.Rows[i].FindControl("CBSelect") as CheckBox;

                if (cb.Checked)
                {
                    Guid accountId = new System.Guid(GridViewAccountList.DataKeys[i].Value.ToString());

                    Zyg.SSO.Core.Business.Account account = Zyg.SSO.Core.Business.Account.Load(accountId);

                    if (account.Apps.Count < 1)
                    {
                        account.DeleteOnSave();
                        account.Save();

                        Zyg.SSO.Core.Business.Log log = new Zyg.SSO.Core.Business.Log();
                        log.AccountId = base.Account.Id;
                        log.ModuleId = Zyg.SSO.Core.Business.Module.Admin.Id;
                        log.Message = string.Format("管理员 {0} 删除了管理员 {1}", base.Account.Email, account.Email);

                        log.Save();
                    }
                    else
                    {
                        hasApp = true;
                    }
                }
            }

            BindData();

            if (hasApp)
                WriteBackScript("alert('删除管理员成功,部分用户由于已经拥有应用而无法删除')");
            else
                WriteBackScript("alert('删除管理员成功')");
        }
    }
}
